package servlet;

import java.awt.Image;
import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.PublicPlayer;

import controller.GameManager;

/**
 * Servlet implementation class Game
 */
@WebServlet("/Game")
public class GameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private GameManager manager;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GameServlet() {
        super();
        manager = GameManager.getInstance();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		RequestDispatcher view = null;
		
		String service = request.getParameter("service");
		String id = request.getParameter("player");
		
		if (service.equals("list_friend")) {
			List<PublicPlayer> friends = manager.getFriends(id);
			request.setAttribute("friends", friends);
            view = request.getRequestDispatcher("index.jsp");
		}
		else if (service.equals("get_image")) {
//		HttpSession session = request.getSession(true);
  //          session.setAttribute("image", friends);
            view = request.getRequestDispatcher("index.jsp");
		}
		else if (service.equals("new_game")) {
			String player_id = request.getParameter("player");
			int game_id = manager.newGame(id, player_id);
			System.out.println("Game " + game_id + " created " + id + " and " + player_id);
		}
		else if (service.equals("continue_game")) {
			Integer game_id = Integer.parseInt(request.getParameter("game_id"));
			String answer = request.getParameter("answer");
			Image image = (Image) request.getSession().getAttribute("image");
			manager.continueGame(game_id, image, answer);
			System.out.println("Game " + game_id + " continue from " + id);
		}
		else if (service.equals("get_games")) {
			List<PublicPlayer> games = manager.getGames(id);
			request.setAttribute("games", games);
			view = request.getRequestDispatcher("jsp/home.jsp");
		}
		
		view.forward(request, response); 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
